// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Data;
using System.Data.Common;
using JetBrains.Annotations;
using Oracle.ManagedDataAccess.Client;
using SnapObjects.Commons;

namespace SnapObjects.Data.Oracle
{
    public class OracleStringTypeMapping : OracleTypeMapping
    {
        private readonly int _maxSpecificSize;

        /// <summary>
        ///     Initializes a new instance of the <see cref="OracleStringTypeMapping" /> class.
        /// </summary>
        /// <param name="dbTypeName"> The name of the database type. </param>
        /// <param name="dbType"> The <see cref="DbType" /> to be used. </param>
        /// <param name="unicode"> A value indicating whether the type should handle Unicode data or not. </param>
        /// <param name="size"> The size of data the property is configured to store, or null if no size is configured. </param>
        public OracleStringTypeMapping(
            [NotNull] string dbTypeName,
            [CanBeNull] DbType? dbType,
            bool unicode = false,
            int? size = null)
            : base(dbTypeName, typeof(string), dbType, unicode, size)
        {
            _maxSpecificSize = this.CalculateSize(unicode, size);
        }

        private int CalculateSize(bool unicode, int? size)
        {
            if (unicode)
            {
                return size.HasValue && size < 2000 ? size.Value : 2000;
            }
            else
            {
                return size.HasValue && size < 4000 ? size.Value : 4000;
            }
        }

        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        public override TypeMapping Clone(string dbTypeName, int? size)
        {
            return new OracleStringTypeMapping(
                           dbTypeName,
                           this.DbType,
                           this.IsUnicode,
                           size);
        }

        /// <summary>
        ///     This API supports the Entity Framework Core infrastructure and is not intended to be used
        ///     directly from your code. This API may change or be removed in future releases.
        /// </summary>
        protected override void ConfigureParameter(DbParameter parameter, IAdoDbParameter adoDbParameter)
        {
            // For strings and byte arrays, set the max length to the size facet if specified, or
            // 8000 bytes if no size facet specified, if the data will fit so as to avoid query cache
            // fragmentation by setting lots of different Size values otherwise always set to
            // -1 (unbounded) to avoid SQL client size inference.

            base.ConfigureParameter(parameter, adoDbParameter);

            var useArraySize = false;

            if (parameter is OracleParameter oracleParameter)
            {
                if (oracleParameter.CollectionType == OracleCollectionType.PLSQLAssociativeArray &&
                    adoDbParameter is AdoDbParameter param)
                {
                    if (oracleParameter.Direction == ParameterDirection.Output)
                    {
                        oracleParameter.ArrayBindSize = param.ArrayBindSize;
                    }

                    useArraySize = true;
                }
                else if ("nchar".Equals(this.DbTypeName, StringComparison.OrdinalIgnoreCase))
                {
                    oracleParameter.OracleDbType = OracleDbType.NChar;
                }
            }

            if (!useArraySize)
            {
                this.SetParameterSize(parameter, adoDbParameter);
            }
        }

        /// <summary>
        ///     Generates the SQL representation of a literal value.
        /// </summary>
        /// <param name="value">The literal value.</param>
        /// <returns>
        ///     The generated string.
        /// </returns>
        protected override string GenerateNonNullSqlLiteral(object value)
        {
            return this.IsUnicode
                           ? $"N'{this.EscapeSqlLiteral((string)value)}'" // Interpolation okay; strings
                           : $"'{this.EscapeSqlLiteral((string)value)}'";
        }

        protected override bool IsAssignable(Type modelType, Type dbType)
        {
            return base.IsAssignable(modelType, dbType) ||
                modelType == typeof(char);
        }

        /// <summary>
        ///     Generates the escaped SQL representation of a literal value.
        /// </summary>
        /// <param name="literal">The value to be escaped.</param>
        /// <returns>
        ///     The generated string.
        /// </returns>
        private string EscapeSqlLiteral([NotNull] string literal)
        {
            return Check.NotNull(literal, nameof(literal)).Replace("'", "''");
        }

        private void SetParameterSize(DbParameter parameter, IAdoDbParameter adoDbParameter)
        {
            var defaultLength = 200;

            if (parameter.Direction == ParameterDirection.Input)
            {
                if (parameter.Value is string str)
                {
                    parameter.Size = str.Length;
                }
                else
                {
                    parameter.Size = defaultLength;
                }
            }
            else if (adoDbParameter is AdoDbParameter adoParm && adoParm.Size > 0)
            {
                parameter.Size = adoParm.Size;
            }
            else
            {
                if (parameter.Value is string strValue)
                {
                    parameter.Size = strValue.Length > _maxSpecificSize ? strValue.Length : _maxSpecificSize;
                }
                else
                {
                    parameter.Size = _maxSpecificSize;
                }
            }
        }
    }

    internal class InternalStringTypeMapping : OracleStringTypeMapping
    {
        private readonly DataContextOptions _contextOptions;
        public InternalStringTypeMapping(DataContextOptions contextOptions) : base("varchar", System.Data.DbType.String)
        {
            _contextOptions = contextOptions;
        }

        protected override void ConfigureParameter(DbParameter parameter, IAdoDbParameter adoDbParameter)
        {
            base.ConfigureParameter(parameter, adoDbParameter);

            if (parameter is OracleParameter p &&
                p.Direction == ParameterDirection.Input &&
                p.CollectionType != OracleCollectionType.PLSQLAssociativeArray &&
                p.OracleDbType == OracleDbType.Varchar2)
            {
                if (parameter.Value != null && parameter.Value is string str)
                {
                    p.Size = str.Length;
                }
            }
        }
    }
}
